

import { useModel } from '@/.umi/plugin-model';
import { addCollectUsingPost, checkCollectStateUsingPost, delCollectUsingPost } from '@/services/music-recommend/collectController';
import { getCover,  MP3_DEFAULT_IMG } from '@/utils/mp3LoadCover';
import { HeartFilled, HeartOutlined, PauseOutlined, PlayCircleOutlined, SoundOutlined, StepBackwardOutlined, StepForwardOutlined, UnorderedListOutlined } from '@ant-design/icons';
import { history } from '@umijs/max';
import { Affix, Col, Row,Image, Slider, Tooltip, Button, message, Popover } from 'antd';
import { Footer } from 'antd/es/layout/layout';
import React, { useState, useEffect, useRef } from 'react';

import ReactHowler from 'react-howler';




interface MyMusicPlayerProps {
  
}

// 简略音乐播放栏
const MyMusicPlayer : React.FC<MyMusicPlayerProps>= () => {

  // 音乐播放控制功能：

  // const progressRef = useRef(null);
  // const [currentTime, setCurrentTime] = useState(0);

  // const [currentSong, setCurrentSong] = useState<API.SongVO>({});
  // const [currentSongIndex, setCurrentSongIndex] = useState(0);

  const [showList,setShowList] = useState(false);
  
  const player = useRef<ReactHowler>(null);
  
  
  const [duration, setDuration] = useState(0);
  const [isSeeking,setIsSeeking] = useState(false);
  const [seek,setSeek] = useState(0.0);
  const [volume,setVolume] = useState(1.0);
  const [showVolume,setShowVolume] = useState(false); // 显示音量滑动条
  // const [mute,setMute] = useState(false); //禁音
  // const [loaded,setLoaded] = useState(false);
  // const [loop,setLoop] = useState(true);

  // song.img
  const [cover,setCover] = useState<string>(MP3_DEFAULT_IMG);

  const {
    songs,
    playing,setPlaying,
    currentSong,setCurrentSong,
    currentSongIndex,setCurrentSongIndex
  }=useModel('musicPlayerModel');


  useEffect(() => {
    const interval = setInterval(() => {
        if (playing && !isSeeking) {
            setSeek(player.current?.seek()?? 0 ); // 更新播放进度
        }
    }, 100); // 每100毫秒更新一次

    return () => clearInterval(interval); // 清理定时器
  }, [isSeeking,playing]);


  useEffect(()=>{
    if(songs.length === 0 ) {
      setCurrentSong({id:-1,name:'none',singerName:'none',tags:'',url:''});
    } else {
      setCurrentSong(songs[currentSongIndex]);
    }
  },[songs.length,currentSongIndex]);

  const handlePlayPause = () =>{
    setPlaying(!playing);
  };

  const handleOnLoad = async () => {
    setDuration(player.current?.duration() ?? 0);
    //loadCover
    const img = await getCover(currentSong.url ?? '');
    setCover(img);
  };

  const handleOnPlay = () => {
    setPlaying(true);
  };

  const handleOnEnd = () => {
    // setPlaying(false);
    // 结束，自动下一首
    playNext();
    
  };

  const handleStop = () =>{
    player.current?.howler.pause();
    setPlaying(false);
  };

  

  const playNext = () => {
    if(currentSongIndex + 1 >= songs.length) {
      setCurrentSongIndex(0);
    } else {
      setCurrentSongIndex(currentSongIndex + 1);
    }
    setSeek(0.0);
  };

  const playPrevious = () => {
    if(currentSongIndex - 1 < 0) {
      setCurrentSongIndex(songs.length - 1);
    } else {
      setCurrentSongIndex(currentSongIndex - 1);
    }
    setSeek(0.0);
  };

  // 进度条
 
  const handleMouseUpSeek = (value)=> {
    player.current?.seek(value);
    setIsSeeking(false);
  };

  const handleSeekingChange = (value) =>{
    setIsSeeking(true);
    setSeek(value);
  };

  const handleVolumeChange = (value:number) =>{
    setVolume(value);
  };


  const formatTime = (secs) =>{
    if (!secs) {
        return '00:00';
    }
    // 取整
    secs = Math.round(secs);

    var minutes = Math.floor(secs / 60) || 0;
    var seconds = (secs - minutes * 60) || 0;

    return String(minutes).padStart(2, '0') + ':' + String(seconds).padStart(2, '0');
  };

  const formateVolume = (value)=>{
    return ''+ value * 100 ;
  };

  // 播放列表
  const handleSwitchSong = (song:API.SongVO,index:number)=>{
    setCurrentSong(song);
    setCurrentSongIndex(index);
    setPlaying(true);
  };


  //收藏功能：

  const [collected,setCollected]= useState(false);
  const getCollectState= async (userId:number,songId:number)=>{
    try{
      const respond = await checkCollectStateUsingPost({userId:userId,songId:songId});
      setCollected(respond.data ?? false );

    } catch(error) {
      console.log(error);
      message.error('获取歌曲收藏数据异常');
    }
    
  };

  useEffect(()=>{
    //get state of collected and set
    if(currentSong.id && currentSong.id > 0){
      const userId = localStorage.getItem('userId');
      getCollectState(Number(userId),currentSong.id);
    } else{
      setCollected(false);
    }
  },[currentSong]);

  const handleCollect = async (song:API.SongVO)=>{
    //handle collect or un-collect
    const userId = localStorage.getItem('userId');
    const songId = song.id;
    try {
      if(collected) {
        const respond = await delCollectUsingPost({userId:Number(userId),songId:songId});
        const result = respond.data ?? false;  
        if(result) {
          setCollected(false);
        }
      }else {
        const respond = await addCollectUsingPost({userId:Number(userId),songId:songId});
        const result = respond.data ?? -1;
        if(result > 0) {
          setCollected(true);
        }   
      }
    } catch (error) {
      console.log(error);
      message.error("收藏操作失败");
    }
    
  };



  return (
    <Affix offsetBottom={1} >
      <Footer className="player-warp" style={{ padding:'10px'}}>
        <Row justify="start" align="middle" style={{ height: '100%' }}>
          <ReactHowler
            src={"/api/song/file/"+currentSong.url}
            playing={playing}
            volume={volume}
            onLoad={handleOnLoad}
            onPlay={handleOnPlay}
            onEnd={handleOnEnd}
            onSeek={() => {setSeek(player.current?.seek() ?? 0);}}
            html5
            preload
            ref={player}
          /> 
          {/* 上一首 暂停/播放 下一首*/}
          <Col span={2} offset={1} >
            <div >
              <StepBackwardOutlined style={{ fontSize:'175%'}} onClick={()=>playPrevious()} />
              {
                playing
                ? <PauseOutlined style={{ fontSize:'175%'}} onClick={handleStop}  />
                : <PlayCircleOutlined style={{ fontSize:'175%'}} onClick={handleOnPlay} />
              }
              <StepForwardOutlined style={{ fontSize:'175%'}} onClick={()=>playNext()} />
            </div>
          </Col>

          {/*歌名 进度条 */}
          <Col span={15} >
            <Row align="middle">
              {/* song picture */}
              <Col span={3} >
                  {/* src={currentSong ? currentSong.img : ''} */}
                  <Image
                   src={cover} 
                   preview={false}
                   style={{padding:8}}
                  ></Image>
              </Col>
              <Col span={20} style={{marginLeft:12}}>
                <a onClick={() => { 
                    if(currentSong.id && currentSong.id > 0) {
                      history.push(`/song?id=${currentSong.id}`);
                    }
                  }}>
                  <span>{(currentSong ? currentSong.name : '')}</span>
                </a>
                {/* 进度条 */}
                <Slider
                  min={0}
                  max={duration}
                  value={seek}
                  step={0.01}
                  tooltip={{formatter:formatTime}}
                  onChange={(val) => handleSeekingChange(val)}
                  onChangeComplete={(val) => handleMouseUpSeek(val)}
                >
                </Slider>
              </Col>
            </Row>
          </Col>

          <Col>
            <Tooltip title={collected?'取消收藏':'收藏'}>
              <Button
                onClick={()=>{handleCollect(currentSong);}}
                shape="circle"
                icon={collected?<HeartFilled style={{color:'red'}}/>:<HeartOutlined/>}
                type="text"
              />
            </Tooltip>
            {/* 播放列表  */}
            <Popover
              content={
                <div style={{ maxHeight: '200%', overflowY: 'auto' }}>
                  {songs.map((song,index) => (
                    <div
                      key={song.id}
                      style={{
                        padding: '8px',
                        display: 'flex',
                        justifyContent: 'space-between', // 使标题和艺术家对齐
                        alignItems: 'center', 
                        color: song.id == currentSong.id ? 'gray' : 'black', // 如果正在播放则灰色
                        // textDecoration: song.id == currentSong.id ? 'line-through' : 'none', // 添加删除线
                        cursor: 'pointer',
                        userSelect: 'none', // 禁止文本选择
                      }}
                      onClick={()=>{
                        handleSwitchSong(song,index);
                      }}
                    >

                      <strong style={{ flex: 1, textAlign: 'left' }}>{song.name}</strong>
                      <span style={{ flex: 1, textAlign: 'center' }}>{song.singerName}</span> 
                    </div>
                  ))}
                </div>
              }
              title={`播放列表 (${songs.length})`}
              trigger="click"
              placement="top"
              open={showList}
              onOpenChange={(open)=>{setShowList(open);}}
            >
              {/* <Tooltip title={`播放列表(${songs.length})`}> */}
              <Button
                onClick={()=> {setShowList(!showList);}}
                shape="circle"
                icon={<UnorderedListOutlined />}
                type="text"
              />
              {/* </Tooltip> */}
            </Popover>
            
            {/* 音量icon */}
            <Popover 
              content={
                <Slider
                  style={{ height: '100px' }}
                  vertical
                  // style={{ display: showVolume ? 'block'  :'none' }}
                  onChange={(val) => handleVolumeChange(val)}
                  value={volume}
                  min={0}
                  max={1}
                  tooltip={{formatter:formateVolume}}
                  step={0.1}
                />
              } 
              trigger="click"
            >
              <Button 
                onClick={() => setShowVolume(!showVolume)}
                shape="circle"
                icon={<SoundOutlined/>}
                type="text"
              />
            </Popover>
            
          </Col>
        </Row>
      </Footer>
    </Affix>
  );
};



export default MyMusicPlayer;


